import config from '../config.js';

export function get(url,param){
    const params=new URLSearchParams();
    for(const key in param){
        if(param.hasOwnProperty(key)){
            params.append(key,param[key]);
        }
    }
    return ajax(url+"?"+params.toString(),{method:"GET"});
}

export function post(url,param){
    if(param){
        const params=new URLSearchParams();
        for(const key in param){
            if(param.hasOwnProperty(key)){
                params.append(key,param[key]);
            }
        }
        return ajax(url,{body:params,method:"POST"});
    }else{
        return ajax(url,{method:"POST"});
    }
}

export  async function ajax(url,option) {
    const response=await fetch(url,option);
    if(response.status!==200){
        if (config.debug) {
            const errMsg = `请求 ${url} 参数 ${option.body} 出错 错误代码 ${response.status} 错误信息 ${response.statusText}`;
            alert(errMsg);
            throw new Error(errMsg);
            //return;
        }
    }

    const result=await response.json();
    return result;
}